'use strict';
var axios = require('axios');
const Controller = require('egg').Controller;


function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并确保是两位数  
  const day = String(date.getDate()).padStart(2, '0'); // 确保日期是两位数  
  const hours = String(date.getHours()).padStart(2, '0'); // 确保小时是两位数  
  const minutes = String(date.getMinutes()).padStart(2, '0'); // 确保分钟是两位数  
  const seconds = String(date.getSeconds()).padStart(2, '0'); // 确保秒是两位数  
  return `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`;
}


let flag = 0;
var token = ''
class DeviceController extends Controller {

  async test() {
    console.log('test')
    const res = await this.ctx.model.Device.create({
      hum: 800,
      tem: 30,
    });
    return 0
  }

  async average() {
    try {
      const data = await this.ctx.model.Device.find({})
        .sort({ _Timestamp: -1 })
        .limit(100)
      // 计算平均值
      if (data.length === 0) {
        return 0;
      }
      const sum = data.reduce((acc, item) => acc + item.wz_velocity, 0);
      console.log('====0', sum)
      this.ctx.body = {
        data: sum / data.length,
      }
    } catch (error) {
      console.error(error);
      return 0;
    }
  }

  async recognition() {
    const { result } = this.ctx.request.body;
    console.log(']]]]]]]]]]', {
      rfid: this.ctx.app.rfid,
      completeTime: formatDate(new Date()),
      processTime: formatDate(new Date(new Date() - 20 * 1000)),
      result: result
    })

    if (flag === 0) {
      flag = 1;
      setTimeout(() => {
        flag = 0;
      }, 15000);

      // 发送到根云积木，更新产品追溯表
      axios.post('http://lowcode.skills-rootcloud.com:8880/api/workflow/hooks/NjcxY2EwZjNkYzY5NjkxOTFkOTYzN2Vh', {
        rfid: this.ctx.app.rfid + '',
        completeTime: formatDate(new Date()),
        processTime: formatDate(new Date(new Date() - 25 * 1000)),
        result: result
      }).then(res => {
        // console.log(res)
      })
    }

    // 下发指令，修改材质，推到不同的槽

    let instructionTemplateId = result ? '_mw10082' : '_mw10081'
    console.log('====', instructionTemplateId)
    axios.post(`http://openapi.rootcloud.com/instruction/v1/thing/instruction-requests`, {
      "assetId": "GZ037GY010103",
      "instructionProperties": {
      },
      "instructionTemplateId": instructionTemplateId,
      "noReply": false,
      "overdueMin": 1440,
      "priority": 0,
      "retryInterval": 600,
      "retryTimes": 0,
      "subId": "history",
      "thingId": "",
      "timeout": 15000,
      "trigger": "offline",
      "type": "LIVE"
    }, {
      headers: {
        Authorization: token
      }
    }
    )
      .then(res => {
      })
      .catch(err => {
        // 如果登录失效，重新获取token
        if (err.status === 401) {
          axios.post('https://openapi.rootcloud.com/account-manage/v2/auth/login', {
            grant_type: 'client_credentials',
            client_id: '202405243fd4bbae6212170e',
            client_secret: 'a474e98535acc4ccc4eb0001a4f9dcd0'
          }).then(res => {
            token = 'Bearer ' + res.data.access_token
          })
        }
      })

    this.ctx.body = {
      code: 1,
      msg: 'ok'
    };
  }


  // 获取电机剩余寿命
  async rlife() {
    this.ctx.body = {
      code: 1,
      data: this.ctx.app.rlife
    };
  }

  //获取振动数据，位移、速度、加速度等
  async getVibrateData() {
    const data = await this.ctx.model.Device.find({})
      .sort({ _Timestamp: -1 })
      .limit(1)

    // console.log('11111', data)

    let _data = data.map((item) => {
      return {
        updatetime: item.updatetime,
        wz_velocity: item.wz_velocity,
        wz_acceleration: item.wz_acceleration,
        wz_displacement: item.wz_displacement,
        wz_addSPeed: item.Wz_addSPeed,
      }
    })
    this.ctx.body = {
      code: 1,
      data: _data
    }
    // console.log('====', data)
  }
}

module.exports = DeviceController;